package role_controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	as "pear-admin-layui-go/app/sys/auth/service"
	rd "pear-admin-layui-go/app/sys/role/domain"
	rs "pear-admin-layui-go/app/sys/role/service"
	rad "pear-admin-layui-go/app/sys/role_auth/domain"
	ras "pear-admin-layui-go/app/sys/role_auth/service"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func RoleAuthEdit(c *gin.Context) {
	var raer rd.RoleAuthEditRequest
	_ = c.ShouldBind(&raer)
	user, _ := login_filter.GetCurrentUser(c)
	raer.CreateTime = time.Now().Unix()
	raer.CreateName = user.Username
	raer.CreateBy = user.Id
	db := ras.RoleAuthEdit(&raer)
	fr.Result(c, db)
}

func AuthSave(c *gin.Context) {
	id, _ := strconv.ParseInt(c.PostForm("id"), 10, 64)
	authIds := c.PostFormArray("authIds[]")
	//log.Println("id = ", id, " authIds = {}", authIds)
	roleAuths := make([]rad.RoleAuth, len(authIds))
	user, _ := login_filter.GetCurrentUser(c)
	for i, v := range authIds {
		roleId, _ := strconv.ParseInt(v, 10, 64)
		roleAuths[i] = rad.RoleAuth{RoleId: id, AuthId: roleId, CreateTime: time.Now().Unix(), CreateBy: user.Id, CreateName: user.Username}
	}
	success, count := ras.SaveRoleAuth(roleAuths)
	r := fr.ROk
	r.Msg = fmt.Sprintf("success = %v, count = %v, diff = %v", success, count, count-success)
	c.JSON(http.StatusOK, r)
}

func AuthPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	auths, _ := as.RoleTree(id)
	tree := AuthTree(auths, 0)
	treeJson, _ := json.Marshal(tree)
	c.HTML(http.StatusOK, "sys/role/auth.html", gin.H{
		"id":       id,
		"authTree": template.HTML(treeJson),
	})
}

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	r := rs.EditPage(id)
	c.HTML(http.StatusOK, "sys/role/edit.html", gin.H{
		"id":     r.Id,
		"name":   r.Name,
		"code":   r.Code,
		"remark": r.Remark,
	})
}

func AuthTree(auths []rad.RoleAuthTreeResponse, pid int64) []map[string]interface{} {
	var tree = make([]map[string]interface{}, 0)
	for _, v := range auths {
		if v.Pid == pid {
			var checked bool
			if v.RoleId != 0 && v.Pid != 0 {
				checked = true
			}
			tree = append(tree, map[string]interface{}{
				"id":       v.Id,
				"title":    v.Name,
				"children": AuthTree(auths, v.Id),
				"checked":  checked,
			})
		}
	}
	return tree
}

func Enable(c *gin.Context) {
	var rer rd.RoleEnableRequest
	_ = c.ShouldBind(&rer)
	user, _ := login_filter.GetCurrentUser(c)
	rer.UpdateTime = time.Now().Unix()
	rer.UpdateBy = user.Id
	rer.UpdateName = user.Username
	db := rs.Enable(&rer)
	fr.Result(c, db)
}

func Edit(c *gin.Context) {
	var rer rd.RoleEditRequest
	_ = c.ShouldBind(&rer)
	user, _ := login_filter.GetCurrentUser(c)
	rer.UpdateTime = time.Now().Unix()
	rer.UpdateBy = user.Id
	rer.UpdateName = user.Username
	db := rs.Edit(&rer)
	fr.Result(c, db)
}

func Save(c *gin.Context) {
	var rsr rd.RoleSaveRequest
	_ = c.ShouldBind(&rsr)
	user, _ := login_filter.GetCurrentUser(c)
	rsr.CreateTime = time.Now().Unix()
	rsr.CreateBy = user.Id
	rsr.CreateName = user.Username
	_, err := rs.Save(&rsr)
	fr.Result(c, err)
}

func AddPage(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/role/add.html", gin.H{})
}

func Page(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/role/role.html", gin.H{
		"enable": template.HTML("<input type=\"checkbox\" name=\"enable\" value=\"{{d.id}}\" lay-skin=\"switch\" lay-text=\"启用|禁用\" {{ d.enable== true ? 'checked' : '' }} lay-filter=\"role-enable\"/>"),
	})
}

func Table(c *gin.Context) {
	var rtr rd.RoleTableRequest
	_ = c.ShouldBind(&rtr)
	roles, count := rs.Table(&rtr)
	var roleTable = make([]rd.RoleTableResponse, len(roles))
	for i, v := range roles {
		roleTable[i] = rd.RoleTableResponse{
			Id:         v.Id,
			Name:       v.Name,
			Code:       v.Code,
			Enable:     v.Enable,
			Remark:     v.Remark,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Count: count,
		Data:  roleTable,
	})
}
